package com.maixy.redisdemo.redis.template;

import com.alibaba.fastjson.JSON;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

/**
 * list redis模板
 * Created by jason on 17-4-14.
 */
@Component
public class ListRedisTemplate extends BaseRedisTemplate {


    @Resource(name = "redisTemplate")
    private RedisTemplate<String, String> redisTemplate;

    public long lpush(String key, String value) {
        return redisTemplate.opsForList().leftPush(key, value);
    }

    /**
     * 移出并获取列表的第一个元素
     * @param key
     * @return
     */
    public String lpop(String key) {
        return redisTemplate.opsForList().leftPop(key);
    }

    /**
     * 在列表中添加一个或多个值(到列表的结尾)
     * @param key
     * @param value
     * @return
     */
    public long rpush(String key, String value) {
        return redisTemplate.opsForList().rightPush(key, value);
    }

    /**
     * 移除并获取列表最后一个元素
     * @param key
     * @return
     */
    public String rpop(String key) {
        return redisTemplate.opsForList().rightPop(key);
    }

    public void rem(String key, Object member) {
        redisTemplate.opsForList().remove(key, 0, member);
    }

    /**
     * 将一个或多个值插入到列表头部
     * @param key
     * @param values
     * @return
     */
    public long rpush(String key, List<String> values) {
        return redisTemplate.opsForList().rightPushAll(key, values);
    }

    public long lpush(String key, List<String> values) {
        return redisTemplate.opsForList().leftPushAll(key, values);

    }
    public long llen(String key) {
        return redisTemplate.opsForList().size(key);
    }

    public List<String> range(String key, long start, long end) {
        return redisTemplate.opsForList().range(key, start, end);
    }

    public <T> List<T> range(String key, long start, long end, Class<T> clazz) {
        List<T> results = new ArrayList<T>();
        List<String> vals = redisTemplate.opsForList().range(key, start, end);
        for (String val : vals) {
            T obj = JSON.parseObject(val, clazz);
            results.add(obj);
        }
        return results;
    }
}
